#!/usr/bin/env python3
"""
诊断 conversation_search 返回空结果的问题
检查 conversations 集合中的数据情况
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "src"))

from src.database.chromadb_client import ChromaDBClient
from src.config import load_config
from src.mcp.tools import MCPTools
from src.core.context_orchestrator import ContextOrchestrator
from src.core.memory_manager import MemoryManager
from src.core.knowledge_processor import KnowledgeProcessor
from src.core.conversation_manager import ConversationManager
from src.database.manager import DatabaseManager

async def diagnose_conversation_search():
    """诊断 conversation_search 功能"""
    print("🔍 开始诊断 conversation_search 功能...")
    
    try:
        # 1. 加载配置
        print("\n📋 加载配置...")
        config = load_config()
        print(f"✅ 配置加载成功")
        
        # 2. 初始化数据库管理器
        print("\n🔗 初始化数据库连接...")
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        print("✅ 数据库连接初始化完成")
        
        # 3. 检查 ChromaDB 连接和 conversations 集合
        print("\n📊 检查 ChromaDB conversations 集合...")
        chromadb_client = db_manager.chromadb_client
        
        # 获取 conversations 集合
        try:
            conversations_collection = chromadb_client.client.get_collection("conversations")
            count = conversations_collection.count()
            print(f"✅ conversations 集合存在，包含 {count} 个文档")
            
            if count > 0:
                # 获取一些示例数据
                results = conversations_collection.get(limit=5)
                print(f"\n📋 conversations 集合示例数据:")
                for i, (doc_id, metadata, document) in enumerate(zip(results['ids'], results['metadatas'], results['documents'])):
                    print(f"  {i+1}. ID: {doc_id}")
                    print(f"     Metadata: {metadata}")
                    print(f"     Document: {document[:100]}..." if len(document) > 100 else f"     Document: {document}")
                    print()
            else:
                print("⚠️  conversations 集合为空")
                
        except Exception as e:
            print(f"❌ 无法访问 conversations 集合: {e}")
            return
        
        # 4. 初始化核心组件
        print("\n🔧 初始化核心组件...")
        memory_manager = MemoryManager(db_manager, config)
        knowledge_processor = KnowledgeProcessor(db_manager, config)
        conversation_manager = ConversationManager(db_manager, config)
        
        await memory_manager.initialize()
        await knowledge_processor.initialize()
        await conversation_manager.initialize()
        print("✅ 核心组件初始化完成")
        
        # 5. 初始化 MCP 工具
        print("\n🎯 初始化 MCP 工具...")
        context_orchestrator = ContextOrchestrator(config)
        await context_orchestrator.initialize()
        
        mcp_tools = MCPTools(context_orchestrator)
        print("✅ MCP 工具初始化完成")
        
        # 6. 测试 conversation_search 功能
        print("\n🧪 测试 conversation_search 功能...")
        
        # 测试1: 搜索特定用户的对话
        print("\n📋 测试1: 搜索 user_id='test_user' 的对话")
        try:
            result1 = await mcp_tools._conversation_search(user_id="test_user", limit=5)
            print(f"✅ 搜索结果: {len(result1.get('conversations', []))} 个对话")
            if result1.get('conversations'):
                for i, conv in enumerate(result1['conversations'][:3]):
                    print(f"  {i+1}. ID: {conv.get('conversation_id')}")
                    print(f"     Title: {conv.get('title')}")
                    print(f"     User: {conv.get('user_id')}")
                    print(f"     Created: {conv.get('created_at')}")
                    print()
            else:
                print("⚠️  未找到任何对话")
        except Exception as e:
            print(f"❌ conversation_search 测试失败: {e}")
            import traceback
            traceback.print_exc()
        
        # 测试2: 搜索包含特定关键词的对话
        print("\n📋 测试2: 搜索包含 'test' 关键词的对话")
        try:
            result2 = await mcp_tools._conversation_search(query="test", limit=5)
            print(f"✅ 搜索结果: {len(result2.get('conversations', []))} 个对话")
            if result2.get('conversations'):
                for i, conv in enumerate(result2['conversations'][:3]):
                    print(f"  {i+1}. ID: {conv.get('conversation_id')}")
                    print(f"     Title: {conv.get('title')}")
                    print(f"     User: {conv.get('user_id')}")
                    print(f"     Created: {conv.get('created_at')}")
                    print()
            else:
                print("⚠️  未找到任何对话")
        except Exception as e:
            print(f"❌ conversation_search 测试失败: {e}")
            import traceback
            traceback.print_exc()
        
        # 7. 检查 conversation_manager 的搜索方法
        print("\n🔍 直接测试 ConversationManager 的搜索方法...")
        try:
            # 直接调用 conversation_manager 的搜索方法
            conversations = await conversation_manager.search_conversations(
                user_id="test_user",
                limit=5
            )
            print(f"✅ ConversationManager 搜索结果: {len(conversations)} 个对话")
            for i, conv in enumerate(conversations[:3]):
                print(f"  {i+1}. {conv}")
        except Exception as e:
            print(f"❌ ConversationManager 搜索失败: {e}")
            import traceback
            traceback.print_exc()
        
        # 8. 检查是否有测试数据创建的对话
        print("\n🔍 检查是否有最近创建的对话...")
        try:
            # 获取所有对话数据
            all_conversations = conversations_collection.get()
            print(f"📊 总共有 {len(all_conversations['ids'])} 个对话")
            
            if all_conversations['ids']:
                print("\n📋 所有对话列表:")
                for i, (doc_id, metadata, document) in enumerate(zip(
                    all_conversations['ids'], 
                    all_conversations['metadatas'], 
                    all_conversations['documents']
                )):
                    print(f"  {i+1}. ID: {doc_id}")
                    print(f"     User: {metadata.get('user_id', 'N/A')}")
                    print(f"     Title: {metadata.get('title', 'N/A')}")
                    print(f"     Created: {metadata.get('created_at', 'N/A')}")
                    print(f"     Document: {document[:100]}..." if len(document) > 100 else f"     Document: {document}")
                    print()
        except Exception as e:
            print(f"❌ 获取所有对话失败: {e}")
        
    except Exception as e:
        print(f"❌ 诊断过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 关闭数据库连接
        try:
            await db_manager.close()
            print("\n✅ 数据库连接已关闭")
        except:
            pass
    
    print("\n🏁 conversation_search 诊断完成")

if __name__ == "__main__":
    asyncio.run(diagnose_conversation_search())